package cn.ai.boot.config.PCF;

import cn.ai.boot.PcmDataFieldConstant;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author jie.zhao@dms365.com
 * @Date 2025/7/29 18:11
 */
public class TEst3333 {
    private static final Logger LOGGER = LoggerFactory.getLogger(TEst3333.class);


    private static List<Map<String, Object>> getData() {
        // 模拟 queryAndAccept 返回的数据列表
        List<Map<String, Object>> mockQueryResult = new ArrayList<>();
        // 非WELD类型数据示例
        Map<String, Object> item1 = new HashMap<>();
        item1.put(PcmDataFieldConstant.PCM_DOCID, "2170-BDG-122003");
        item1.put(PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, "PCN001");
        item1.put(PcmDataFieldConstant.PCM_UCI, "000138A8-0000-0000-6A15-7E0C506724063333333");
        item1.put(PcmDataFieldConstant.PCM_TYPE, "PIPE");
        item1.put(PcmDataFieldConstant.PCM_DESCRIBE, "管道");
        item1.put(PcmDataFieldConstant.PCM_F_COMPONENT_NO, "FCN001");
        item1.put(PcmDataFieldConstant.PCM_R_COMPONENT_NO, "RCN001");
        item1.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "PATH001");
        mockQueryResult.add(item1);

// WELD类型数据示例 - 直管焊口
        Map<String, Object> item2 = new HashMap<>();
        item2.put(PcmDataFieldConstant.PCM_DOCID, "2170-BDG-122004");
        item2.put(PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, "PCN002");
        item2.put(PcmDataFieldConstant.PCM_UCI, "000138AA-0000-0000-370F-4C30B466B00A");
        item2.put(PcmDataFieldConstant.PCM_TYPE, PcmCompTypeConstant.WELD);
        item2.put(PcmDataFieldConstant.PCM_DESCRIBE, PcmWeldDescConstant.PIPE_WELD);
        item2.put(PcmDataFieldConstant.PCM_R_COMPONENT_NO, "RCN002");
        item2.put(PcmDataFieldConstant.PCM_WLDGING_ORD_NO, "WON001");
        item2.put(PcmDataFieldConstant.PCM_SKEY, "SKEY001");
        item2.put(PcmDataFieldConstant.PCM_PIPELINE_NUMBER, "PN001");
        item2.put(PcmDataFieldConstant.PCM_DN, "DN100");
        item2.put(PcmDataFieldConstant.PCM_NPS, "NPS4");
        item2.put(PcmDataFieldConstant.PCM_COORDINATE_1, "100,200,300");
        mockQueryResult.add(item2);

        // WELD类型数据示例 - 其他焊口
        Map<String, Object> item3 = new HashMap<>();
        item3.put(PcmDataFieldConstant.PCM_DOCID, "40-09^2F0015-2160-FRD-0902N");
        item3.put(PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, "PCN003");
        item3.put(PcmDataFieldConstant.PCM_UCI, "0001388C-0000-0000-1E0F-4C30B466B00A");
        item3.put(PcmDataFieldConstant.PCM_TYPE, PcmCompTypeConstant.WELD);
        item3.put(PcmDataFieldConstant.PCM_DESCRIBE, "其他焊口");
        item3.put(PcmDataFieldConstant.PCM_R_COMPONENT_NO, "RCN003");
        item3.put(PcmDataFieldConstant.PCM_WLDGING_ORD_NO, "WON002");
        mockQueryResult.add(item3);

// 另一个非WELD类型数据示例
        Map<String, Object> item4 = new HashMap<>();
        item4.put(PcmDataFieldConstant.PCM_DOCID, "40-09^2F0014-2160-FRD-0901W");
        item4.put(PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, "PCN004");
        item4.put(PcmDataFieldConstant.PCM_UCI, "00013885-0000-0000-170F-4C30B466B00A");
        item4.put(PcmDataFieldConstant.PCM_TYPE, "ELBOW");
        item4.put(PcmDataFieldConstant.PCM_DESCRIBE, "弯头");
        item4.put(PcmDataFieldConstant.PCM_F_COMPONENT_NO, "FCN004");
        item4.put(PcmDataFieldConstant.PCM_R_COMPONENT_NO, "RCN004");
        item4.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "PATH004");
        mockQueryResult.add(item4);
        return mockQueryResult;
    }

    // 创建静态模拟数据
    private static final List<Map<String, Object>> MOCK_GROUP_LIST = new ArrayList<>();

    static {
        // 初始化模拟数据
        Map<String, Object> groupItem1 = new HashMap<>();
        groupItem1.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "FCN001");
        groupItem1.put(PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, "PCN_DIFF_001");
        groupItem1.put(PcmDataFieldConstant.PCM_UCI, "UCI_GROUP_001");
        groupItem1.put(PcmDataFieldConstant.PCM_TYPE, "PIPE");
        MOCK_GROUP_LIST.add(groupItem1);

        Map<String, Object> groupItem2 = new HashMap<>();
        groupItem2.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "RCN004");
        groupItem2.put(PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, "PCN_DIFF_002");
        groupItem2.put(PcmDataFieldConstant.PCM_UCI, "UCI_GROUP_002");
        groupItem2.put(PcmDataFieldConstant.PCM_TYPE, "ELBOW");
        MOCK_GROUP_LIST.add(groupItem2);

        Map<String, Object> groupItem3 = new HashMap<>();
        groupItem3.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "RCN001");
        groupItem3.put(PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, "PCN_DIFF_004");
        groupItem3.put(PcmDataFieldConstant.PCM_UCI, "UCI_GROUP_005");
        groupItem3.put(PcmDataFieldConstant.PCM_TYPE, "REDUCER");
        MOCK_GROUP_LIST.add(groupItem3);
    }

    // 添加静态模拟数据
    private static final List<Map<String, Object>> MOCK_PIPE_DATA_LIST = new ArrayList<>();

    static {
        // 初始化模拟管道数据
        Map<String, Object> pipeData1 = new HashMap<>();
        pipeData1.put(PcmDataFieldConstant.PCM_COMPONENT_IDENTIFIER, "COMP_ID_001");
        pipeData1.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "RCN002");
        pipeData1.put(PcmDataFieldConstant.PCM_TYPE, PcmCompTypeConstant.PIPE);
        MOCK_PIPE_DATA_LIST.add(pipeData1);

        Map<String, Object> pipeData2 = new HashMap<>();
        pipeData2.put(PcmDataFieldConstant.PCM_COMPONENT_IDENTIFIER, "COMP_ID_002");
        pipeData2.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "RCN003");
        pipeData2.put(PcmDataFieldConstant.PCM_TYPE, PcmCompTypeConstant.PIPE);
        MOCK_PIPE_DATA_LIST.add(pipeData2);

        Map<String, Object> pipeData3 = new HashMap<>();
        pipeData3.put(PcmDataFieldConstant.PCM_COMPONENT_IDENTIFIER, "COMP_ID_003");
        pipeData3.put(PcmDataFieldConstant.PCM_COMPONENT_PATH, "RCN001");
        pipeData3.put(PcmDataFieldConstant.PCM_TYPE, PcmCompTypeConstant.PIPE);
        MOCK_PIPE_DATA_LIST.add(pipeData3);
    }

    public static void main(String[] args) throws IOException {
        List<Map<String, Object>> mainDatas = new ArrayList<>();
        mainDatas.add(new HashMap<>());
        TEst3333 tEst3333 = new TEst3333();
        tEst3333.genBlueprintTask(mainDatas);
    }

    /**
     * 图纸生成，循环调用时list传一个，
     */
    public void genBlueprintTask(List<Map<String, Object>> mainDatas) throws IOException {
        for (Map<String, Object> mainData : mainDatas) {
            // ===============================step 1 取出数据 start===============================
            // 所有的文件
            Set<String> docIds = new HashSet<>();
            // 4 在设计明细表中找到的数据，过滤保留 预制件编号｛pcm_prefab_components_no｝不为空的数据，获取 UCI｛pcm_uci｝的值
            Set<String> prefabComponentsNoUci = new HashSet<>();
            // 5 通过第4点，在设计明细表中找到的数据，筛选得到 元件类型｛pcm_type｝不为“WELD”的记录，获取 UCI｛pcm_uci｝的值，并在PCF文件中找到对应的范围；
            Set<String> noWeldUci = new HashSet<>();
            // 6 存储非WELD类型且预制件编号不为空的记录，按预制件编号分组 组内记录记为A1
            Map<String, List<Map<String, Object>>> nonWeldGroupedByPrefabNo = new HashMap<>();
            // 7 通过第4点，在设计明细表中找到的数据，筛选得到 元件类型｛pcm_type｝为“WELD”的记录，获取 UCI｛pcm_uci｝的值，并在PCF文件中找到对应的范围；
            List<Map<String, Object>> weldUci = new ArrayList<>();
            // 8 把直管焊口信息写入PCF文件中 筛选 元件类型｛pcm_type｝为“WELD”且 描述｛pcm_describe｝为“直管焊口”的数据；
            List<Map<String, Object>> weldPipe = new ArrayList<>();
            // step1 取出数据

            // 提取并去重docId
            for (Map<String, Object> item : getData()) {
                // 获取文档id
                String docId = MapUtils.getString(item, PcmDataFieldConstant.PCM_DOCID);
                if (StringUtils.isNotEmpty(docId)) {
                    docIds.add(docId);
                }
                // 预制件编号
                String prefabNo = MapUtils.getString(item, PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO);
                //在设计明细表中找到的数据，过滤保留 预制件编号｛pcm_prefab_components_no｝不为空的数据，获取 UCI｛pcm_uci｝的值
                if (StringUtils.isNotEmpty(prefabNo)) {
                    prefabComponentsNoUci.add(MapUtils.getString(item, PcmDataFieldConstant.PCM_UCI, StringUtils.EMPTY));
                    // 在设计明细表中找到的数据，筛选得到 元件类型｛pcm_type｝不为“WELD”的记录，获取 UCI｛pcm_uci｝的值，并在PCF文件中找到对应的范围
                    if (PcmCompTypeConstant.WELD.equals(MapUtils.getString(item, PcmDataFieldConstant.PCM_TYPE))) {
                        weldUci.add(item);
                    }
                    if (!PcmCompTypeConstant.WELD.equals(MapUtils.getString(item, PcmDataFieldConstant.PCM_TYPE))) {
                        noWeldUci.add(MapUtils.getString(item, PcmDataFieldConstant.PCM_UCI, StringUtils.EMPTY));
                        // 按预制件编号分组
                        nonWeldGroupedByPrefabNo.computeIfAbsent(prefabNo, k -> new ArrayList<>()).add(item);
                    }
                }
                if (PcmCompTypeConstant.WELD.equals(MapUtils.getString(item, PcmDataFieldConstant.PCM_TYPE)) && PcmWeldDescConstant.PIPE_WELD.equals(MapUtils.getString(item, PcmDataFieldConstant.PCM_DESCRIBE))
                ) {
                    weldPipe.add(item);
                }
            }
            //6
            List<Map<String, Object>> prefabComponentsNoUciForNonWeld = getPrefabComponentsNoUciForNonWeld(nonWeldGroupedByPrefabNo);

            LOGGER.info("step1.data:prefabComponentsNoUci:{}", prefabComponentsNoUci);
            LOGGER.info("step1.data:noWeldUci:{}", noWeldUci);
            LOGGER.info("step1.data:nonWeldGroupedByPrefabNo:{}", nonWeldGroupedByPrefabNo);
            LOGGER.info("step1.data:weldUci:{}", weldUci);
            LOGGER.info("step1.data:weldPipe:{}", weldPipe);
            // ===============================step 1 取出数据 end===============================

            // ===============================step 2 组装PCF文件 start===============================
            //2.1 获取到文件id，获取pcf文件，文件夹属性出图配置
            Map<String, PCFProcessor> pcfProcessorMap = processPcfContent(docIds);

            //2.1 获取PCF文件，顶部 UNITS-BORE 的值
            for (PCFProcessor processor : pcfProcessorMap.values()) {
                // 2获取PCF文件，顶部 UNITS-BORE 的值
                processor.setUnitsBore(processor.getValueByKey(PcmPcfConstant.UNITS_BORE));
                // 3 判断整个PCF文件中，是否有 FABRICATION-ITEM的标识，如果有替换为ERECTION-ITEM
                processor.replaceAllIdentifiers(PcmPcfConstant.FABRICATION_ITEM, PcmPcfConstant.ERECTION_ITEM);
                // 处理第5点数据
                replaceIdentifiers(processor, noWeldUci);
                //处理第6点数据
                insertPrefabIdentifiers(processor, prefabComponentsNoUciForNonWeld);
                // 处理第7点数据
                updateWeldAttributes(processor, weldUci);
                // 处理第8点数据
                appendWeldSections(processor, weldPipe);

                processor.saveToFile();
            }
            // ===============================step 2 组装PCF文件 end===============================

            // ===============================step 3 发送至eZiso插件 start===============================
            // 生成新的pcf文件


            // ===============================step 3 发送至eZiso插件 end===============================
        }
        // TODO 发送MQ
        // TODO 文件挂载
        // TODO 文件归档
    }


    // 修改 processPcfContent 方法以支持真实文件读取
    private Map<String, PCFProcessor> processPcfContent(Set<String> docIds) {
        Map<String, PCFProcessor> pcfProcessorMap = new HashMap<>();

        // 为每个 docId 创建一个模拟的 PCFProcessor
        for (String docId : docIds) {
            // 根据docId生成文件名
            String fileName = "D:\\download\\testpcf\\x\\" + docId + ".pcf";
            // 创建 PCFProcessor 实例
            PCFProcessor processor = null;
            try {
                processor = new PCFProcessor(fileName);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            processor.setFileName(fileName);
            pcfProcessorMap.put(docId, processor);
        }

        return pcfProcessorMap;
    }

    /**
     * 处理第5点数据 查询该元件范围内的信息，把ERECTION-ITEM 替换为 FABRICATION-ITEM；
     */
    private void replaceIdentifiers(PCFProcessor processor, Set<String> noWeldUci) {
        // 将FABRICATION-ITEM替换为ERECTION-ITEM
        processor.replaceAllIdentifiers(PcmPcfConstant.FABRICATION_ITEM, PcmPcfConstant.ERECTION_ITEM);

        // 处理非焊接件范围内的标识符替换
        for (String uci : noWeldUci) {
            List<int[]> ranges = processor.getValueRanges(uci);
            processor.replaceIdentifiersInRange(PcmPcfConstant.ERECTION_ITEM, PcmPcfConstant.FABRICATION_ITEM, ranges);
        }
    }

    /**
     * 处理第6点数据 在该元件范围内，末尾新增一行，以 PREFABRICATED 作为标识，把该元件在设计明细表中 预制件编号｛pcm_prefab_components_no｝的值进行赋值。
     */
    private void insertPrefabIdentifiers(PCFProcessor processor, List<Map<String, Object>> prefabComponentsNoUciForNonWeld) {
        for (Map<String, Object> uciMap : prefabComponentsNoUciForNonWeld) {
            String uci = MapUtils.getString(uciMap, PcmDataFieldConstant.PCM_UCI);
            List<int[]> ranges = processor.getValueRanges2(uci);
            String a1PrefabNo = MapUtils.getString(uciMap, PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, StringUtils.EMPTY);
            processor.insertLineAtRangeEnds(PcmPcfConstant.PREFABRICATED + a1PrefabNo, ranges);
        }
    }


    /**
     * 处理第7点数据
     * 更新PCF文件该范围内【SKEY】标识的值为“WW”；
     * 更新PCF文件该范围内【WELD-ATTRIBUTE3】标识的值为“Shop weld”；
     * 更新PCF文件该范围内【WELD-ATTRIBUTE4】标识的值为“Fabricator”；
     * 获取设计明细表，该条记录 焊口序号｛pcm_wldging_ord_no｝的值，更新到PCF文件该范围内【REPEAT-WELD-IDENTIFIER】标识的值；
     */
    private void updateWeldAttributes(PCFProcessor processor, List<Map<String, Object>> weldUci) {
        for (Map<String, Object> uciMap : weldUci) {
            String uci = MapUtils.getString(uciMap, PcmDataFieldConstant.PCM_UCI);
            String pcmWldgingOrdNo = MapUtils.getString(uciMap, PcmDataFieldConstant.PCM_WLDGING_ORD_NO, StringUtils.EMPTY);
            List<int[]> ranges = processor.getValueRanges(uci);

            processor.updateKeyValueInRange(PcmPcfConstant.SKEY, PcmPcfConstant.SKEY_VAL, ranges);
            processor.updateKeyValueInRange(PcmPcfConstant.WELD_ATTRIBUTE3, PcmPcfConstant.WELD_ATTRIBUTE3_VAL, ranges);
            processor.updateKeyValueInRange(PcmPcfConstant.WELD_ATTRIBUTE4, PcmPcfConstant.WELD_ATTRIBUTE4_VAL, ranges);
            processor.updateKeyValueInRange(PcmPcfConstant.REPEAT_WELD_IDENTIFIER, pcmWldgingOrdNo, ranges);
        }
    }


    // 辅助方法：根据条件获取模拟管道数据
    private List<Map<String, Object>> getMockPipeDataList(String rComponentNo) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 根据查询条件筛选模拟数据
        for (Map<String, Object> mockItem : MOCK_PIPE_DATA_LIST) {
            String componentPath = MapUtils.getString(mockItem, PcmDataFieldConstant.PCM_COMPONENT_PATH, StringUtils.EMPTY);
            String type = MapUtils.getString(mockItem, PcmDataFieldConstant.PCM_TYPE, StringUtils.EMPTY);

            // 模拟查询条件: componentPath = rComponentNo AND type = PIPE
            if (componentPath.equals(rComponentNo) && PcmCompTypeConstant.PIPE.equals(type)) {
                result.add(mockItem);
            }
        }

        return result;
    }

    /**
     * 取第六点数据
     */
    private List<Map<String, Object>> getPrefabComponentsNoUciForNonWeld
    (Map<String, List<Map<String, Object>>> nonWeldGroupedByPrefabNo) {
        List<Map<String, Object>> prefabComponentsNoUciForNonWeld = new ArrayList<>();
        for (Map.Entry<String, List<Map<String, Object>>> entry : nonWeldGroupedByPrefabNo.entrySet()) {
            String prefabNo = entry.getKey();
            List<Map<String, Object>> a1List = entry.getValue(); // A1记录
            // 遍历组内每条A1记录
            for (Map<String, Object> a1 : a1List) {
                String uci = MapUtils.getString(a1, PcmDataFieldConstant.PCM_UCI);
                if (StringUtils.isEmpty(uci)) {
                    continue;
                }
                String fComponentNo = MapUtils.getString(a1, PcmDataFieldConstant.PCM_F_COMPONENT_NO, StringUtils.EMPTY);
                String rComponentNo = MapUtils.getString(a1, PcmDataFieldConstant.PCM_R_COMPONENT_NO, StringUtils.EMPTY);
                if (StringUtils.isNotEmpty(fComponentNo) || StringUtils.isNotEmpty(rComponentNo)) {
                    // 根据前后元件查询设计明细表
                    DaSdkQuery queryAll = new DaSdkQuery();
                    queryAll.setSelects(Lists.newArrayList(
                            PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO,
                            PcmDataFieldConstant.PCM_COMPONENT_PATH
                    ));
                    queryAll.or(DaSdkCondition.create(PcmDataFieldConstant.PCM_COMPONENT_PATH).eq(fComponentNo));
                    queryAll.or(DaSdkCondition.create(PcmDataFieldConstant.PCM_COMPONENT_PATH).eq(rComponentNo));
                    // 直接使用预定义的模拟数据替代数据库查询
                    List<Map<String, Object>> groupList = getMockGroupList(fComponentNo, rComponentNo);
                    // 在所有设计数据中查找匹配的A2记录（元件路径与前/后元件编号匹配）
                    // 获取A2记录的预制件编号 判断A1与A2的预制件编号是否不同\获取A1记录的UCI值用于在PCF中查找范围
                    for (Map<String, Object> designItem : groupList) {
                        String componentPath = MapUtils.getString(designItem, PcmDataFieldConstant.PCM_COMPONENT_PATH, StringUtils.EMPTY);
                        String a2PrefabNo = MapUtils.getString(designItem, PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, StringUtils.EMPTY);
                        if (StringUtils.isNotEmpty(componentPath)) {
                            if ((componentPath.equals(fComponentNo) || componentPath.equals(rComponentNo))
                                    && !Objects.equals(a2PrefabNo, prefabNo)) {
                                prefabComponentsNoUciForNonWeld.add(a1);
                                break;
                            }
                        }
                    }
                }
            }
        }
        return prefabComponentsNoUciForNonWeld;
    }

    // 辅助方法：根据条件获取模拟数据
    private List<Map<String, Object>> getMockGroupList(String fComponentNo, String rComponentNo) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 根据查询条件筛选模拟数据
        for (Map<String, Object> mockItem : MOCK_GROUP_LIST) {
            String componentPath = MapUtils.getString(mockItem, PcmDataFieldConstant.PCM_COMPONENT_PATH, StringUtils.EMPTY);
            // 模拟 or 条件查询 (componentPath = fComponentNo OR componentPath = rComponentNo)
            if (componentPath.equals(fComponentNo) || componentPath.equals(rComponentNo)) {
                result.add(mockItem);
            }
        }

        return result;
    }

    private void appendWeldSections(PCFProcessor processor,
                                    List<Map<String, Object>> weldPipe
    ) {
        // 起始点
        int maxIdentifierByKey = processor.getMaxIdentifierByKey(PcmPcfConstant.COMPONENT_IDENTIFIER);
        // 获取UNITS-BORE值以确定单位制
        String unitsBore = processor.getUnitsBore();
        // 为每个直管焊口生成WELD段
        for (int i = 0; i < 2; i++) {
            Map<String, Object> weldData = weldPipe.get(0);
            // 构建WELD段内容
            String weldSection = buildWeldSection(weldData, unitsBore, maxIdentifierByKey + i + 1);
            // 将WELD段追加到PCF文件中
            processor.appendLinesToFileEnd(Arrays.asList(weldSection));
        }
    }

    /**
     * 构建单个WELD段内容
     */
    private String buildWeldSection(Map<String, Object> weldData, String unitsBore, int componentIdentifier) {
        DaSdkQuery pipeQuery = new DaSdkQuery();
        pipeQuery.setSelects(Arrays.asList(PcmDataFieldConstant.PCM_COMPONENT_IDENTIFIER));
        pipeQuery.and(DaSdkCondition.create(PcmDataFieldConstant.PCM_COMPONENT_PATH).eq(MapUtils.getString(weldData, PcmDataFieldConstant.PCM_R_COMPONENT_NO)));
        pipeQuery.and(DaSdkCondition.create(PcmDataFieldConstant.PCM_TYPE).eq(PcmCompTypeConstant.PIPE));
        String rComponentNo = MapUtils.getString(weldData, PcmDataFieldConstant.PCM_R_COMPONENT_NO);

        // 使用辅助方法获取模拟数据
        List<Map<String, Object>> pipeDataList = getMockPipeDataList(rComponentNo);
        Map<String, Object> first = pipeDataList.getFirst();
        String masterComponentId = MapUtils.getString(first, PcmDataFieldConstant.PCM_COMPONENT_IDENTIFIER, StringUtils.EMPTY);

        // 两个END-POINT
        String endPoint1 = buildEndPoint(weldData, unitsBore);
        String endPoint2 = buildEndPoint(weldData, unitsBore);

        // SKEY
        String skey = MapUtils.getString(weldData, PcmDataFieldConstant.PCM_SKEY, StringUtils.EMPTY);

        // REPEAT-WELD-IDENTIFIER
        String repeatWeldIdentifier = MapUtils.getString(weldData, PcmDataFieldConstant.PCM_WLDGING_ORD_NO, StringUtils.EMPTY);

        // UCI
        String uci = MapUtils.getString(weldData, PcmDataFieldConstant.PCM_UCI, StringUtils.EMPTY);

        // WELD-ATTRIBUTE1
        String weldAttribute1 = MapUtils.getString(weldData, PcmDataFieldConstant.PCM_PIPELINE_NUMBER, StringUtils.EMPTY);

        // WELD-ATTRIBUTE2
        String weldAttribute2 = getDnOrNpsValue(weldData, unitsBore);

        // WELD-ATTRIBUTE3 和 WELD-ATTRIBUTE4 (根据预制件编号判断)
        String prefabNo = MapUtils.getString(weldData, PcmDataFieldConstant.PCM_PREFAB_COMPONENTS_NO, StringUtils.EMPTY);
        String weldAttribute3 = determineWeldAttribute3(prefabNo);
        String weldAttribute4 = determineWeldAttribute4(prefabNo);

        // 使用模板格式化
        return String.format(PcmPcfConstant.WELD_SECTION_TEMPLATE,
                componentIdentifier,
                masterComponentId,
                endPoint1,
                endPoint2,
                skey,
                repeatWeldIdentifier,
                uci,
                "",
                weldAttribute1,
                weldAttribute2,
                weldAttribute3,
                weldAttribute4);
    }

    /**
     * 根据预制件编号确定WELD-ATTRIBUTE4值
     */
    private String determineWeldAttribute4(String prefabNo) {
        // 根据业务逻辑确定值，示例：
        if (StringUtils.isNotEmpty(prefabNo)) {
            return "By Pipe Fabricator"; // 有预制件编号时为预制厂
        }
        return "By Pipe Erector"; // 无预制件编号时为承包商
    }

    /**
     * 根据预制件编号确定WELD-ATTRIBUTE3值
     */
    private String determineWeldAttribute3(String prefabNo) {
        // 根据业务逻辑确定值，示例：
        if (StringUtils.isNotEmpty(prefabNo)) {
            return "Shop weld"; // 有预制件编号时为工厂焊口
        }
        return "ield weld at job site, including offshore"; // 无预制件编号时为现场焊口
    }

    /**
     * 构建END-POINT值
     */
    private String buildEndPoint(Map<String, Object> weldData, String unitsBore) {
        String coordinate = MapUtils.getString(weldData, PcmDataFieldConstant.PCM_COORDINATE_1, StringUtils.EMPTY);
        String dnOrNps = getDnOrNpsValue(weldData, unitsBore);

        // 5个空格分隔
        return coordinate + "     " + dnOrNps;
    }


    /**
     * 根据单位制获取DN或NPS值
     */
    private String getDnOrNpsValue(Map<String, Object> data, String unitsBore) {
        String value;
        if ("INCH".equals(unitsBore)) {
            // 英制取NPS
            value = MapUtils.getString(data, PcmDataFieldConstant.PCM_NPS, StringUtils.EMPTY);
            // 如果NPS为空，则取DN
            if (StringUtils.isEmpty(value)) {
                value = MapUtils.getString(data, PcmDataFieldConstant.PCM_DN, StringUtils.EMPTY);
            }
        } else {
            // 公制取DN
            value = MapUtils.getString(data, PcmDataFieldConstant.PCM_DN, StringUtils.EMPTY);
            // 如果DN为空，则取NPS
            if (StringUtils.isEmpty(value)) {
                value = MapUtils.getString(data, PcmDataFieldConstant.PCM_NPS, StringUtils.EMPTY);
            }
        }
        return value;
    }
}
